import Vue from "vue";
import VueRouter from "vue-router";

// 引入路由组件
const Details = () => import("../components/Details.vue");
const Login = () => import("../components/Login.vue");
const Register = () => import("../components/RegisterView.vue");
const Index = () => import("../components/Index.vue");
const Cart = () => import("../components/Cart.vue");
const Lise = () => import("../components/Lise.vue");
const SearchList = () => import("../components/SearchList.vue");
const Info = () => import("../components/MyInfo.vue");
const news = () => import("../components/news.vue");
const serve = () => import("../components/serve.vue");
const Order = () => import("../components/Order.vue");
const news_tall = () => import("../components/news_tall");
// Vue使用VueRouter
Vue.use(VueRouter);
//重写路由对象的push函数，处理重复点同一个路径时出现异常
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};
import { Toast } from "vant";
Toast.setDefaultOptions({ duration: 2000 });
let map = new Map([
  ["/", "登录"],
  ["/index", "首页"],
  ["/register", "注册页"],
  ["/order", "下单页"],
  ["/lise", "列表页"],
  ["/searchList", "搜索页"],
  ["/info", "我的"],
  ["/details", "详情页"],
  ["/cart", "购物车"],
  ["/news", "消息"],
  ["/serve", "服务页"],
  ["/news_tall", "对话"],
]);
// 创建路由对象集合
let routes = [
  { path: "/index", component: Index },
  { path: "/", component: Login },
  { path: "/register", component: Register },
  { path: "/lise", component: Lise },
  { path: "/searchList", component: SearchList },
  { path: "/info", component: Info },
  {
    path: "/details",
    component: Details,
  },
  { path: "/cart", component: Cart },
  { path: "/order", component: Order },
  { path: "/news", component: news },
  { path: "/serve", component: serve },
  { path: "/news_tall", component: news_tall },
];
// 创建路由器对象
let router = new VueRouter({ routes });
// 全局路由守卫
router.beforeEach((to, from, next) => {
  console.log(to, from);
  let toPath = to.path;
  let fromPath = from.path;
  //设置标题
  document.title = map.get(toPath);
  console.log(toPath, fromPath);
  if (toPath === "/" || toPath === "/register") {
    // 登录和注册放行
    return next();
  }
  let str = sessionStorage.getItem("user-login");
  if (!str) {
    Toast.fail("请先登录！");
    return next("/");
  }
  let token = JSON.parse(str).token;
  if (!token) {
    Toast.fail("请先登录！");
    return next("/");
  }
  next();
});
// 导出router
export default router;
